// GroundingDINO.js
const COCOLabelLoader = require('../../../../../labels/vision/detection/COCOLabelLoader');

class GroundingDINOParser {
    constructor(app) {
        this.app = app;
        this.loader = new COCOLabelLoader(this.app);
    }

    // 解析返回的结果（只是转换格式）
    convertResult(result) {
        // console.log(`>> GroundingDINOParser convertResult result = `, result);
        const bboxes = result['det_node.bboxes'];
        let labelResult = this.loader.create(bboxes, null, result['det_node.labels'], result['det_node.scores']);
        // console.log(`labelResult = `, labelResult);
        return labelResult;
    }

    // 解析返回的结果（保存结果）
    // datasetInfo：数据集信息  
    // recordInfo：存储的记录
    // result：解析的结果
    async saveResult(datasetInfo, recordInfo, result) {
        // console.log(`>> GroundingDINOParser saveResult datasetInfo = `, datasetInfo, `recordInfo = `, recordInfo, `result = `, result);

        // 组装保存所需要的参数
        let labels = this.convertResult(result);
        let params = {
            dataset_id: datasetInfo.id,
            dataset_supertype: datasetInfo.dataset_supertype,
            dataset_type: datasetInfo.dataset_type,
            label_format: datasetInfo.label_format,
            pairs_id: recordInfo.pairs_id,
            image_url: recordInfo.image_path,
            label_url: recordInfo.label_path,
            labels: labels.map((label) => {
                const date = new Date();
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                const timestamp = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                return {
                    id: label.id,
                    type: 'detection',
                    method: 'autolabel',
                    author: 'GroundingDINO',
                    timestamp: timestamp,
                    score: label.score,
                    data: label
                }
            })
        };
        // console.log(params);

        // 保存标注结果
        try {
            await this.loader.save(params);
            return true;
        } catch (error) {
            console.log('==> GroundingDINOParser saveResult error:', error);
            return false;
        }
    }
}

module.exports = GroundingDINOParser;
